import { DeleteOutlined, EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Dropdown, message, Modal } from 'antd';
import React, { ReactDOM, useEffect, useRef, useState } from 'react';
import { history } from 'umi';
// 引入样式
// import styles from './index.less';
import './index.less';
// 图片
import { delDocuments, getDocuments } from '@/services/ant-design-pro/api';
import moment from 'moment';
import { stringify } from 'querystring';
import EmptyComponent from './com/EmptyComponent';
// import FullScreenLoading from './com/FullScreenLoading';

const write = (item: any) => {
  let query = '';
  if (item) {
    query = stringify({ id: item.document_uuid || '' });
  }
  history.push({
    pathname: `/conversation?${query}`,
  });
};
// loading

// 有历史记录组件
const StatefulComponent: React.FC = () => {
  // const arr = new Array(100).fill(0)
  const [id, setId] = useState(null);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [isScroll, setIsScroll] = useState(true);
  const [loading, setLoading] = useState(false);
  const [isEmpty, setIsEmpty] = useState(false);
  const [historyList, setHistoryList] = useState([]);
  console.log('🚀 ~ file:index  line:45 -----', historyList);
  const getData = async () => {
    console.log('🚀 ~ file:index  line:44 -----请求接口');
    const params = {
      page,
      per_page: 35,
    };
    setLoading(true);
    const res = await getDocuments(params);
    if (res.code === 0) {
      setLoading(false);
      const arr = [...historyList, ...res.data.documents];
      setHistoryList(arr);
      setTotal(res.data.total_count);
      setIsEmpty(res.data.total_count < 1);
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
    console.log('loading', loading);
  };
  const containerRef = useRef<ReactDOM.Container | null>(null);
  useEffect(() => {
    const unlisten = history.listen(({ location }) => {
      // 路由变化时执行的逻辑
      console.log('Route changed:', location.pathname);
      if (location.pathname !== '/writeHome') {
        setIsScroll(false);
      } else if (location.pathname === '/writeHome') {
        setTimeout(() => {
          setIsScroll(true);
        });
      }
    });

    return () => {
      unlisten();
    };
  }, [history]);
  useEffect(() => {
    console.log('🚀 ~ file:index  line:83 -----');
    getData();
  }, [page]);
  useEffect(() => {
    getData();
  }, []);
  const onScroll = () => {
    if (historyList.length >= total && total !== 0) return;
    const container = containerRef.current;
    const scrollTop = container.scrollTop; // 滚动条顶部距离容器顶部的位置
    const scrollHeight = container.scrollHeight; // 容器的内容高度
    const clientHeight = container.clientHeight; // 可见区域的高度
    const distanceToBottom = scrollHeight - scrollTop - clientHeight; // 距离底部的距离
    console.log('🚀 ~ file:index  line:96 -----', isScroll);
    if (distanceToBottom <= 0 && isScroll) {
      setPage(page + 1);
    }
  };
  const [open, setOpen] = useState(false);

  const showModal = () => {
    setOpen(true);
  };

  const hideModal = () => {
    setOpen(false);
  };
  const onConfirm = async () => {
    await delDocuments(id);
    const data = historyList.filter((item) => item.document_uuid !== id);
    setHistoryList(data);
    message.success('删除成功');
    hideModal();
    setIsEmpty(data.length < 1);
  };
  const onClick: (v: any, item: any) => void = (v, item) => {
    setId(item.document_uuid);
    if (v.key === '2') {
      showModal();
    }
  };
  // const addCls = [styles.cardItem, styles.cardMore];
  const items = [
    // {
    //   label: (
    //     <div>
    //       <CopyOutlined />
    //       <span style={{ marginLeft: '5px' }}>复制文档</span>
    //     </div>
    //   ),
    //   key: '1',
    // },
    {
      label: (
        <div>
          <DeleteOutlined />
          <span style={{ marginLeft: '5px' }}>删除文档</span>
        </div>
      ),
      key: '2',
    },
  ];
  return (
    <div>
      {historyList.length ? (
        <div className="statefulComponent" onScroll={() => onScroll()} ref={containerRef}>
          <div className="header">
            <h3>我的文档</h3>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => write()}>
              新建文档
            </Button>
          </div>
          <div className="card">
            {historyList.map((item, index) => {
              return (
                <div className="cardItem" key={index}>
                  <div
                    onClick={() => write(item)}
                    style={{ display: 'flex', flexDirection: 'column' }}
                  >
                    <div className="title">
                      <div className="titleCon f10">{item.user_command}</div>
                    </div>
                    <div className="aiContent">{item.abstract}</div>
                  </div>
                  <div className="footer">
                    <div className="f9">
                      {moment(item.updated_timestamp).format('YYYY-MM-DD HH:mm:ss')}
                    </div>
                    <Dropdown menu={{ items, onClick: (v) => onClick(v, item) }}>
                      <span className="more" style={{ cursor: 'pointer' }}>
                        <EllipsisOutlined />
                      </span>
                    </Dropdown>
                  </div>
                </div>
              );
            })}
            <div className="cardItem cardMore" onClick={write}>
              <PlusOutlined className="text" />
              <div className="text">新建文档</div>
            </div>
          </div>
          <Modal
            title="确认删除"
            open={open}
            onOk={onConfirm}
            onCancel={hideModal}
            width={350}
            okText="确认"
            cancelText="取消"
            footer={[
              <Button key="back" onClick={hideModal}>
                取消
              </Button>,
              <Button type="primary" danger onClick={onConfirm} key="confirm">
                确认
              </Button>,
            ]}
          >
            <p>确定删除该文档吗?</p>
          </Modal>
        </div>
      ) : (
        isEmpty && <EmptyComponent />
      )}
    </div>
  );
};
const WriteHome: React.FC = () => {
  return (
    <div className="page-container">
      {/* <Header title="公文写作共享实习生"></Header> */}
      {/* <KeepAlive>
        <StatefulComponent />
      </KeepAlive> */}
      <StatefulComponent />
    </div>
  );
};
export default WriteHome;
